<template>
  <Form ref='regForm' class="xtx-form" v-slot='{ errors }'>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field :rules='schema.accountApi' v-model='form.account' name='account' class="input" type="text" placeholder="请输入用户名" />
      </div>
      <div class="error" v-if='errors.account'>{{errors.account}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field :rules='schema.mobile' v-model='form.mobile' name='mobile' class="input" type="text" placeholder="请输入手机号" />
      </div>
      <div class="error" v-if='errors.mobile'>{{errors.mobile}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field :rules='schema.code' v-model='form.code' name='code' class="input" type="text" placeholder="请输入验证码" />
        <span @click='sendCode' class="code">{{timer? `${timer}秒后重发`: '发送验证码'}}</span>
      </div>
      <div class="error" v-if='errors.code'>{{errors.code}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :rules='schema.password' v-model='form.password' name='password' class="input" type="password" placeholder="请输入密码" />
      </div>
      <div class="error" v-if='errors.password'>{{errors.password}}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field :rules='schema.rePassword' v-model='form.rePassword' name='rePassword' class="input" type="password" placeholder="请确认密码" />
      </div>
      <div class="error" v-if='errors.rePassword'>{{errors.rePassword}}</div>
    </div>
    <a @click='handleSubmit' href="javascript:;" class="submit">立即提交</a>
  </Form>
</template>

<script>
import { reactive, ref } from 'vue'
import Message from '@/components/library/Message.js'
import { Form, Field } from 'vee-validate'
import schema from '@/utils/validate-schema.js'
import { useIntervalFn } from '@vueuse/core'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user.js'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

export default {
  name: 'CallbackPatch',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      required: true
    }
  },
  setup (props) {
    const store = useStore()
    const router = useRouter()
    const form = reactive({
      account: '',
      mobile: '',
      code: '',
      password: '',
      rePassword: ''
    })
    // 实现验证码倒计时效果
    const timer = ref(0)
    const { pause, resume } = useIntervalFn(() => {
      if (timer.value <= 0) {
        pause()
      } else {
        timer.value -= 1
      }
    }, 1000, {
      immediate: false
    })

    // 发送验证码
    const sendCode = async () => {
      // 点击发送验证码按钮时，验证手机号
      const isOk = schema.mobile(form.mobile)
      if (isOk === true) {
        resume()
        timer.value = 60
        try {
          const ret = await userQQPatchCode(form.mobile)
          if (ret && ret.msg === '操作成功') {
            Message({ type: 'success', text: '发送验证码成功' })
          } else {
            Message({ type: 'error', text: ret.message })
          }
        } catch {
          Message({ type: 'error', text: '发送验证码失败' })
        }
      } else {
        // 手机号格式错误
        regForm.value.setFieldError('mobile', isOk)
      }
    }
    // 操作表单
    const regForm = ref(null)

    // 注册账号提交表单
    const handleSubmit = async () => {
      const isOk = await regForm.value.validate()
      if (isOk) {
        // 表单验证通过
        try {
          const ret = await userQQPatchLogin(props.unionId, {
            account: form.account,
            mobile: form.mobile,
            code: form.code,
            password: form.password
          })
          if (ret && ret.result) {
            // 注册成功，保存用户信息，跳转到主页面
            store.dispatch('user/updateUser', ret.result)
            router.push('/')
          }
        } catch {
          Message({ type: '', text: '注册失败' })
        }
      }
    }
    return { regForm, form, timer, schema, sendCode, handleSubmit }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
